package com.jy.admin.services.cashPocket;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.google.common.collect.Lists;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jy.admin.db.dao.CeAgentAccountDao;
import com.jy.admin.db.dao.CeCommentPushLogDao;
import com.jy.admin.db.dao.CeMerchantDao;
import com.jy.admin.db.dao.CeOrdersDetailDao;
import com.jy.admin.db.entity.*;
import com.jy.admin.enums.ApiTypeEnum;
import com.jy.admin.enums.OrderStatusEnum;
import com.jy.admin.enums.OrderSyncStatusEnum;
import com.jy.admin.enums.SivanWalletCollectionTagEnum;
import com.jy.admin.jobs.BaseJobHandler;
import com.jy.admin.services.BaseCrawlerService;
import com.jy.admin.services.cashPocket.vo.ClOrderInputVo;
import com.jy.admin.services.cashPocket.vo.ClOrderReceiveRequest;
import com.jy.admin.services.cashPocket.vo.ClRepaymentRequest;
import com.jy.admin.services.cashPocket.vo.ClUserInfoInputVo;
import com.robert.vesta.util.IdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2022/1/3
 * Time: 8:46 下午
 */
@Service
public class SivanWalletService extends BaseCrawlerService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SivanWalletService.class);

    @Autowired
    private CeOrdersDetailDao ordersDetailDao;

    @Autowired
    private CeMerchantDao merchantDao;

    @Autowired
    private CeCommentPushLogDao commentPushLogDao;

    @Autowired
    private CeAgentAccountDao agentAccountDao;

    @PostConstruct
    public void init() {
        BaseJobHandler.merchantAndServiceMap.put("yashrupaya", this);
        BaseJobHandler.merchantAndServiceMap.put("miracle115pocket", this);
    }
    public static String execCurl(String[] cmds) {
        ProcessBuilder process = new ProcessBuilder(cmds);
        Process p;
        try {
            p = process.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
                builder.append(System.getProperty("line.separator"));
            }
            return builder.toString();

        } catch (IOException e) {
            System.out.print("error");
            e.printStackTrace();
        }
        return null;
    }

    public boolean autoLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isAutoLoginOpen()) {
            CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
            String url = merchant.getApiDomain() + "/hs/admin/auth/login";
            LOGGER.info("== 开始请求登录接口 ==,url:{}", url);
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            JSONObject params = new JSONObject();
            params.put("phoneNo", agentAccount.getAccount());
            params.put("code", agentAccount.getPassword());

            String fileName = "/home/java/open-collection/cks/" + agentAccount.getMerchantCode() + "_" + agentAccount.getAccount() + ".txt";
            String[] command = {"curl", "-c", fileName, "--location", "--request", "POST", url, "--header", "Content-Type: application/json", "--data-raw", JsonStream.serialize(params)};
            String loginRes = execCurl(command);
            LOGGER.info("== testJT  ==,loginRes:{}", loginRes);

            String cookie = null;
            try {
                Path path = Paths.get(fileName);
                byte[] data = Files.readAllBytes(path);
                String result = new String(data, "utf-8");
                String[] s1 = result.split("hs-admin");
                cookie = "hs-admin=" + s1[1].trim();
                LOGGER.info("== testJT  ==,cookie:{}", cookie);

                String personalListUrl = merchant.getApiDomain()+"/hs/admin/menu/personalList";
                String[] command2 = {"curl", "--location", "--request", "POST", personalListUrl, "--header", "Content-Type: application/json", "--header", "Cookie:" + cookie + ";isLogin=ok;"};
                String personalRes = execCurl(command2);
                LOGGER.info("== testJT  ==,personalRes:{}", personalRes);
                cookie = cookie + ";isLogin=ok;isGoogleAuth=ok;";

                if (StringUtils.isNotEmpty(personalRes) && JsonIterator.deserialize(personalRes).get("code").toInt() == 200) {
                    JSONObject requestHeader = new JSONObject();
                    requestHeader.put("cookie", cookie);
                    requestHeader.put("Content-Type", "application/json");
                    agentAccount.setRequestHeader(requestHeader.toString());
                    agentAccount.setLoginDt(new Date());
                    agentAccount.setLoginStatus(1);
                    agentAccountDao.updateByPrimaryKey(agentAccount);
                    return true;
                } else {
                    LOGGER.info("== 自动登录失败 ==");
                    agentAccount.setLoginStatus(2);
                    agentAccountDao.updateByPrimaryKey(agentAccount);
                }
            } catch (IOException e) {
                LOGGER.error("== testJT  ==", e);
                LOGGER.info("== 自动登录失败 ==");
                agentAccount.setLoginStatus(2);
                agentAccountDao.updateByPrimaryKey(agentAccount);
                return false;
            }
        } else {
            LOGGER.info("== 未开启自动登录 ==");
            agentAccount.setLoginStatus(2);
            agentAccountDao.updateByPrimaryKey(agentAccount);
        }
        return false;
    }

    @Override
    public boolean hasLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isLoginStatusUseCache()) {
            return agentAccount.getLoginStatus() == 1;
        }

        if (agentAccount.getLoginStatus() == 2) {
            LOGGER.error("== 账号 token不可用 ==,account:{}", agentAccount.getAccount());
            boolean isLogin = autoLogin(agentAccount);
            return isLogin;
        }
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/hs/admin/auth/getInfo";
        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 开始请求Token ==,url:{}", url);

        JSONObject params = new JSONObject();
        String[] command2 = {"curl", "--location", "--request", "POST", url, "--header", "Content-Type: application/json", "--header", "Cookie:" + headers.get("cookie") ,"--data-raw", params.toString()};
        String result = LittleOrangeService.execCurl(command2);
        LOGGER.info("==SivanWallet==,res:{}", result);
        if (JsonIterator.deserialize(result).get("code").toInt() != 200) {
            LOGGER.error("== 请求接口数据出错 当前账号token无效==，agentCode:{}", agentAccount.getAgentCode());
            return autoLogin(agentAccount);
        }

        return true;
    }

    @Override
    public void refresh(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== SivanWallet 开始刷新数据 ==,account:{}", agentAccount.getAccount());
        updateOrderList(agentAccount);

        LOGGER.info("== 订单数据更新完成 开始更新订单关联数据==，account:{}", agentAccount.getAccount());
        updateOrderDetailInfo(agentAccount);

        LOGGER.info("== 订单关联数据已经更新完成==，account:{}", agentAccount.getAccount());
    }

    @Override
    public void updateOrderList(CeAgentAccountEntity agentAccount) {
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));
        JSONObject params = new JSONObject();
        String url = "";
        if (agentAccount.getStage().equals("d-1") || agentAccount.getStage().equals("d0")) {
            url = merchant.getApiDomain() + "/hs/admin/orderToday/dclist";
//            params.put("fstartTime", DateUtil.getDate("yyyy-MM-dd") + " 00:00:00");
//            params.put("fendTime", DateUtil.getDate("yyyy-MM-dd") + " 23:59:59");
        } else if (agentAccount.getStage().equals("s1")) {
            url = merchant.getApiDomain() + "/hs/admin/orderOverdue/dclist";
        }
        LOGGER.info("== 开始请求订单列表 ==,url:{}", url);
        params.put("isDc", true);
        params.put("pageNum", 1);
        params.put("pageSize", 999);
        params.put("status", "0");
        String[] command2 = {"curl", "--location", "--request", "POST", url, "--header", "Content-Type: application/json", "--header", "Cookie:" + headers.get("cookie") ,"--data-raw", params.toString()};
        String result = execCurl(command2);
        if (JsonIterator.deserialize(result).get("code").toInt() != 200) {
            LOGGER.error("== 请求接口数据出错 ==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            return;
        }

        List<Any> resultsList = JsonIterator.deserialize(result).get("data").asList();

        //查询今天该账号的所有有效订单
        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());

        //对比订单数据
        if (CollectionUtils.isEmpty(activeOrders)) {
            LOGGER.info("== 存在未拉取订单 ==，agentCode:{},size:{}", agentAccount.getAgentCode(), resultsList.size());
            resultsList.forEach(item -> {
                try {
                    String orderNo = item.get("orderNo").toString();
                    CeOrdersEntity todayOneByOrderNo = ordersDao.getTodayOneByOrderNoAndAgentCode(orderNo, agentAccount.getAgentCode());
                    if (todayOneByOrderNo == null) {
                        LOGGER.info("==更新的时候发现有新的订单==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), orderNo);
                        CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                .setAgentCode(agentAccount.getAgentCode())
                                .setMerchantCode(agentAccount.getMerchantCode())
                                .setOrderNo(orderNo)
                                .setOrderInfo(item.toString())
                                .setStatus(OrderStatusEnum.active.getStatus())
                                .setCreateDt(new Date())
                                .setCollectionNo(IdUtils.genId() + "");
                        ordersDao.insert(ceOrdersEntity);
                    }
                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), item.get("borrowId").toString(), e);
                }
            });
        } else {
            resultsList.forEach(item -> {
                try {
                    String orderNo = item.get("orderNo").toString();
                    CeOrdersEntity OneByOrderNo = ordersDao.getTodayOneByOrderNoAndAgentCode(orderNo, agentAccount.getAgentCode());
                    if (OneByOrderNo == null) {
                        LOGGER.info("== 列表为空,插入订单 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), orderNo);
                        CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                .setAgentCode(agentAccount.getAgentCode())
                                .setMerchantCode(agentAccount.getMerchantCode())
                                .setOrderNo(orderNo)
                                .setOrderInfo(item.toString())
                                .setStatus(OrderStatusEnum.active.getStatus())
                                .setCreateDt(new Date())
                                .setCollectionNo(IdUtils.genId() + "");
                        ordersDao.insert(ceOrdersEntity);
                    }
                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), item.get("orderNo").toString(), e);
                }
            });
            LOGGER.info("== 订单减少 ==,agentCode:{}，size:{}", agentAccount.getAgentCode(), resultsList.size());
            activeOrders.forEach(item -> {
                try {
                    String id = JsonIterator.deserialize(item.getOrderInfo()).get("orderNo").toString();
                    boolean hasOrder = false;
                    for (int i = 0; i < resultsList.size(); i++) {
                        Any child = resultsList.get(i);
                        String orderNo = child.get("orderNo").toString();
                        if (id.equals(orderNo)) {
                            LOGGER.info("== 当前订单存在 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), orderNo);
                            hasOrder = true;
                            break;
                        }

                    }
                    if (!hasOrder) {
                        LOGGER.info("== 当前订单不存在 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), id);
                        if (item.getStatus().equals(OrderStatusEnum.active.getStatus())) {
                            item.setStatus(OrderStatusEnum.updated.getStatus());
                            ordersDao.updateByPrimaryKey(item);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.error("== 更新订单发生异常 ==,account:{},orderNo:{}", agentAccount.getAccount(), JsonIterator.deserialize(item.getOrderInfo()).get("id").toString(), e);
                }
            });

        }
        LOGGER.info("== 订单刷新处理完成 ==");
    }

    @Override
    public void updateOrderDetailInfo(CeAgentAccountEntity agentAccount) {

        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());
        if (CollectionUtils.isEmpty(activeOrders)) {
            return;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());

        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        activeOrders.forEach(order -> {

            try {
                boolean hasDetailData = order.getDetailStatus() == 1;
                Map<String, String> infoMap = new HashMap<>();

                Any orderInfo = JsonIterator.deserialize(order.getOrderInfo());
                String id = orderInfo.get("id").toString();
                JSONObject param = new JSONObject();
                param.put("overdueId", id);
                String baseInfoUrl = "";
                if (agentAccount.getStage().equals("d-1") || agentAccount.getStage().equals("d0")) {
                    baseInfoUrl = merchant.getApiDomain() + "/hs/admin/orderToday/detail";
                } else {
                    baseInfoUrl = merchant.getApiDomain() + "/hs/admin/orderOverdue/detail";
                }
                String[] command2 = {"curl", "--location", "--request", "POST", baseInfoUrl, "--header", "Content-Type: application/json", "--header", "Cookie:" + headers.get("cookie") ,"--data-raw", param.toString()};
                String baseInfoResult = execCurl(command2);
                if (JsonIterator.deserialize(baseInfoResult).get("code").toInt() != 200) {
                    LOGGER.info("== 获取详情出错 ==,agentCode:{},err:{}", agentAccount.getAgentCode(), JsonIterator.deserialize(baseInfoResult).get("message").toString());
                    return;
                }
                infoMap.put("repaymentInfo", JsonIterator.deserialize(baseInfoResult).get("data").toString());
                String remainMoney = JsonIterator.deserialize(baseInfoResult).get("data").get("leftMoney").toString();
                LOGGER.info("== 还款金额 remainMoney==,remainMoney:{},orderNo:{}", remainMoney, orderInfo.get("orderNo").toString());
                updateRemainMoney(order.getCollectionNo(), remainMoney);
                Any baseInfo = JsonIterator.deserialize(baseInfoResult).get("data").get("userRealnameInfo");
                List<String> images = Lists.newArrayList();
                if (!baseInfo.get("idcardFrontPhoto").toString().equals("")) {
                    String url = baseInfo.get("idcardFrontPhoto").toString();
                    images.add(url);
                }
                if (!baseInfo.get("idcardBackPhoto").toString().equals("")) {
                    String url = baseInfo.get("idcardBackPhoto").toString();
                    images.add(url);
                }
                if (!baseInfo.get("panPhoto").toString().equals("")) {
                    String url = baseInfo.get("panPhoto").toString();
                    images.add(url);
                }
                if (!baseInfo.get("livingPhoto").toString().equals("")) {
                    String url = baseInfo.get("livingPhoto").toString();
                    images.add(url);
                }
                infoMap.put("images", JsonStream.serialize(images));
                LOGGER.info("== 获取成功 images==");
                updateImages(order.getOrderNo(), JsonStream.serialize(images), order.getMerchantCode());


                if (!hasDetailData) {

                    infoMap.put("baseInfo", baseInfo.toString());
                    LOGGER.info("== 获取成功 baseInfo==");

                    List<Any> contactDatas = JsonIterator.deserialize(baseInfoResult).get("data").get("userAuthInfo").get("emergencyContactInfos").asList();
                    JSONArray contacts = new JSONArray();
                    for (Any vo : contactDatas) {
                        JSONObject j1 = new JSONObject();
                        j1.put("name", vo.get("name").toString().equals("") ? "no" : vo.get("name").toString());
                        if (!vo.get("phoneNr").toString().equals("")) {
                            j1.put("phone", vo.get("phoneNr").toString().replaceAll(" ",""));
                            contacts.add(j1);
                        }
                    }
                    LOGGER.info("== 获取成功 contact==");
                    infoMap.put("contactInfo", contacts.toString());

                    CeOrdersDetailEntity contactInfoUrlDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());
                    if (contactInfoUrlDetail == null) {
                        String contactInfoUrl = merchant.getApiDomain() + "/hs/admin/user/contacts";
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("userId", orderInfo.get("userId").toString());
                        String[] command = {"curl", "--location", "--request", "POST", contactInfoUrl, "--header", "Content-Type: application/json", "--header", "Cookie:" + headers.get("cookie") ,"--data-raw", jsonObject.toString()};
                        String contactInfoResult = execCurl(command);
                        LOGGER.info("== 获取成功 contactInfo==");

                        try {
                            List<Any> contactList = JsonIterator.deserialize(contactInfoResult).get("data").asList();
                            if (CollectionUtils.isNotEmpty(contactList)) {
                                JSONArray contactsList = new JSONArray();
                                int size = Math.min(contactList.size(), 500);
                                for (int i = 0; i < size; i++) {
                                    Any vo = contactList.get(i);
                                    JSONObject j1 = new JSONObject();
                                    j1.put("name", vo.get("contactsName").toString().equals("") ? "no" : vo.get("contactsName").toString());
                                    if (!vo.get("contactsPhone").toString().equals("")) {
                                        String phone = vo.get("contactsPhone").toString();
                                        if (!phone.equalsIgnoreCase("unknown")) {
                                            j1.put("phone", phone);
                                            contactsList.add(j1);
                                        }

                                    }
                                }
                                JSONObject jsonData = new JSONObject();
                                jsonData.put("contacts", contactsList);

                                String contactUrl = uploadContact(order.getOrderNo(), jsonData.toString());
                                LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);
                                infoMap.put("contactUrl", contactUrl);
                            } else {

                                JSONObject jsonData = new JSONObject();
                                jsonData.put("contacts", contacts);

                                String contactUrl = uploadContact(order.getOrderNo(), jsonData.toString());
                                LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);
                                infoMap.put("contactUrl", contactUrl);
                            }

                        } catch (Exception e) {
                            LOGGER.error("== 通讯录转换错误 ==", e);
                        }
                    } else {
                        contactInfoUrlDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(contactInfoUrlDetail);
                    }

                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        if (byKeyAndMerchantAndOrderNo == null) {
                            CeOrdersDetailEntity ordersDetailEntity = new CeOrdersDetailEntity()
                                    .setOrderNo(order.getOrderNo())
                                    .setMerchantCode(order.getMerchantCode())
                                    .setDataKey(k)
                                    .setDetailInfo(infoMap.get(k));
                            ordersDetailDao.insert(ordersDetailEntity);
                        } else {
                            byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                            ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                        }

                    });
                } else {
                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                        ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                    });
                }

                order.setDetailStatus(1);
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 程序处理有异常 ==", e);
                order.setDetailStatus(2);
                ordersDao.updateByPrimaryKey(order);
            }
        });

        LOGGER.info("== 程序处理完成 ==");
    }

    @Override
    public void compostCollectionData(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== compostCollectionData ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== compostCollectionData  没有需要同步的订单 ==，agentCode:{},syncStatus:{}", agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
            return;
        }

        LOGGER.info("== compostCollectionData  需要同步的订单 ==，size:{},account:{}", todayListBySyncStatusAndAgent.size(), agentAccount.getAccount());

        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                LOGGER.info("== 构建推送信息 基础信息 开始==,collectionNo:{},syncStatus:{}", order.getCollectionNo(), order.getSyncStatus());
                CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());

                String appName = agentAccount.getAppName();
                ClOrderReceiveRequest request = new ClOrderReceiveRequest()
                        .setOrderBillNo(order.getCollectionNo())
                        .setTradeNo(order.getCollectionNo())
                        .setProductType(appName)
                        .setAppName(appName)
                        .setOriginOrderNo(order.getOrderNo())
                        .setAccount(order.getAgentCode())
                        .setAccount_id(agentAccount.getId())
                        .setClientCode(order.getMerchantCode())
                        .setProductCode(appName)
                        .setUserCode(IdUtils.genId() + "");


                String borrowCapital = repaymentInfo.get("deviceMoney").toString();
                String actualAmount = repaymentInfo.get("lendMoney").toString();
                String paidAmount = repaymentInfo.get("payMoney").toString();
                String remainMoney = repaymentInfo.get("leftMoney").toString();
                String serviceFee = StringUtils.isEmpty(repaymentInfo.get("service").toString())?"0":repaymentInfo.get("service").toString();
                String overdueDays = repaymentInfo.get("expireDays").toString();
                String lateFee = repaymentInfo.get("overMoney").toString();

                LOGGER.info("== 构建推送信息 计算逾期罚息利率 开始==,borrowCapital:{}，overdueDays:{}.lateFee:{}", borrowCapital, overdueDays, lateFee);
                String overdueRatio = "0";
                if (!overdueDays.equals("0")) {
                    overdueRatio = new BigDecimal(lateFee).divide(new BigDecimal(overdueDays), 2, BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(borrowCapital), 4, BigDecimal.ROUND_HALF_UP).toString();
                }
                LOGGER.info("== 构建推送信息 订单信息 开始==,collectionNo:{}", order.getCollectionNo());

                CeOrdersDetailEntity personalInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "baseInfo", order.getOrderNo());
                Any personalInfoJson = JsonIterator.deserialize(personalInfo.getDetailInfo());


                ClOrderInputVo orderInputVo = new ClOrderInputVo()
                        .setBorrowType(repaymentInfo.get("isOlduser").toInt() == 0 ? 1 : 2)
                        .setBorrowCapital(borrowCapital)
                        .setChannel(appName)
                        .setCapitalCode(appName)
                        .setInterest("0")
                        .setDeductAmount("0")
                        .setLateFeeRatio(overdueRatio)
                        .setServiceFee(serviceFee)
                        .setLateServiceFee("0")
                        .setReceivedCapital(actualAmount)
                        .setPaidAmount(paidAmount)
                        .setReceivedDate(DateUtil.getDate(new Date(repaymentInfo.get("loanTime").toLong() * 1000 - 9000000), "yyyy-MM-dd"))
                        .setRepaymentDate(DateUtil.getDate(new Date(repaymentInfo.get("expireTime").toLong() * 1000 - 9000000), "yyyy-MM-dd"))
                        .setRemainMoney(remainMoney)
                        .setTotalMoney(remainMoney);

                request.setOrderInfo(orderInputVo);


                LOGGER.info("== 构建推送信息 个人信息 开始==,collectionNo:{}", order.getCollectionNo());

                String aadhaarNo = personalInfoJson.get("idcardNo").toString();
                String pancardNo = personalInfoJson.get("panId").toString();
                String email = "no";
                String mobile = repaymentInfo.get("userPhone").toString();
                String name = personalInfoJson.get("idName").toString();
                int gender = personalInfoJson.get("gender").toString().equals("MALE") ? 1 : 0;
                int maritalStatus = 0;
                int education = 0;
                String address = personalInfoJson.get("address").toString();
                String pinCode = "no";
                String state = "no";
                String city = "no";
                String birthDay = DateUtil.getDate(DateUtil.getDate(personalInfoJson.get("birthday").toString(), "dd/MM/yyyy"), "yyyy-MM-dd");


                CeOrdersDetailEntity contactInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactInfo", order.getOrderNo());
                List<Any> contactInfoJson = JsonIterator.deserialize(contactInfo.getDetailInfo()).asList();

                String parentName = "no";
                String parentPhone = "no";
                String friendName = "no";
                String friendMobile = "no";
                if (contactInfoJson.size() >= 2) {
                    parentName = contactInfoJson.get(0).get("name").toString();
                    parentPhone = contactInfoJson.get(0).get("phone").toString();
                    friendName = contactInfoJson.get(1).get("name").toString();
                    friendMobile = contactInfoJson.get(1).get("phone").toString();
                }


                CeOrdersDetailEntity contactUrlEntity = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());


                CeOrdersDetailEntity iamges = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "images", order.getOrderNo());
                List<Any> anies = JsonIterator.deserialize(iamges.getDetailInfo()).asList();

                List<String> images = new ArrayList<>();
                anies.forEach(v -> {
                    images.add(v.toString());
                });

                ClUserInfoInputVo userInfoInputVo = new ClUserInfoInputVo()
                        .setUserLanguage("")
                        .setAadhaarNo(aadhaarNo)
                        .setPanCardNo(pancardNo)
                        .setAddress(address)
                        .setBirthday(birthDay)
                        .setCity(city)
                        .setEmail(email)

                        .setContact1Mobile(parentPhone)
                        .setContact1Name(parentName)
                        .setContact1Relative(1)

                        .setContact2Mobile(friendMobile)
                        .setContact2Name(friendName)
                        .setContact2Relative(6)

                        .setEducation(education)
                        .setKycNo(aadhaarNo)
                        .setMobile(mobile)

                        .setMarriedStatus(maritalStatus)
                        .setMarriedStatus(maritalStatus)
                        .setName(name)
                        .setPinCode(pinCode)
                        .setState(state)

                        .setSex(gender)
                        .setContactUrl(contactUrlEntity.getDetailInfo())
                        .setImages(images);

                request.setUserInfo(userInfoInputVo);

                LOGGER.info("== 构建推送信息 完成==,collectionNo:{}", order.getCollectionNo());

                CePushLogEntity pushLogEntity = pushLogDao.selectByCollectionNo(order.getCollectionNo());
                if (pushLogEntity == null) {
                    pushLogEntity = new CePushLogEntity()
                            .setCollectionNo(order.getCollectionNo())
                            .setDetailInfo(JsonStream.serialize(request))
                            .setStatus(1);
                    pushLogDao.insert(pushLogEntity);
                } else {
                    pushLogEntity.setDetailInfo(JsonStream.serialize(request));
                    pushLogDao.updateByPrimaryKey(pushLogEntity);
                }


                LOGGER.info("== 构建推送信息 保存信息完成==,collectionNo:{}", order.getCollectionNo());
                order.setSyncStatus(OrderSyncStatusEnum.data_ready.getStatus());
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 构建推送信息 发生异常==,collectionNo:{}", order.getCollectionNo(), e);
                order.setSyncStatus(OrderSyncStatusEnum.data_fail.getStatus());
                ordersDao.updateByPrimaryKey(order);
            }
        });

    }

    @Override
    public void pushDataToCollection(CeAgentAccountEntity agentAccount) {
        super.pushDataToCollection(agentAccount);
    }

    /**
     * 获取新的借贷信息的详细内容是需要 在这个方法执行之前的
     *
     * @param agentAccount
     */
    @Override
    public void checkOrdersPaidStatus(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 检查订单支付情况 ==");
        List<CeOrdersEntity> waitingPaidCheckOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.updated.getStatus());
        if (CollectionUtils.isEmpty(waitingPaidCheckOrders)) {
            LOGGER.info("== 检查订单支付情况 没有状态更新的订单==,size:{}", waitingPaidCheckOrders.size());
            return;
        }

        LOGGER.info("== 检查订单支付情况==,size:{}", waitingPaidCheckOrders.size());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));


        waitingPaidCheckOrders.forEach(order -> {

            JSONObject params = new JSONObject();
            params.put("pageNum", 1);
            params.put("pageSize", 999);
            String url = "";
            if (agentAccount.getStage().equals("d-1") || agentAccount.getStage().equals("d0")) {
                url = merchant.getApiDomain() + "/hs/admin/orderToday/todayPayOrderList";
                params.put("startTime", DateUtil.getDate("yyyy-MM-dd") + " 00:00:00");
                params.put("endTime", DateUtil.getDate("yyyy-MM-dd") + " 23:59:59");
            } else if (agentAccount.getStage().equals("s1")) {
                url = merchant.getApiDomain() + "/hs/admin/orderOverdue/overduePayOrderList";
                params.put("type", agentAccount.getStage());
                params.remove("StartTime");
                params.remove("EndTime");
            }
            LOGGER.info("== 开始请求已订单列表 ==,url:{}", url);
            String[] command = {"curl", "--location", "--request", "POST", url, "--header", "Content-Type: application/json", "--header", "Cookie:" + headers.get("cookie") ,"--data-raw", params.toString()};
            String result = execCurl(command);
            Any resultJson = JsonIterator.deserialize(result);
            if (resultJson.get("code").toInt() != 200) {
                LOGGER.info("== 订单详情异常 ==");
                return;
            }
            List<Any> listData = resultJson.get("data").asList();
            boolean isRepay = false;
            for (int i = 0; i < listData.size(); i++) {
                if (order.getOrderNo().equals(listData.get(i).get("orderNo").toString())) {
                    isRepay = true;
                    break;
                }
            }
            if (isRepay) {
                LOGGER.info("== 订单已还款 ==,OrderNo:{}", order.getOrderNo());
                order.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
                order.setStatus(OrderStatusEnum.paid_update.getStatus());
                ordersDao.updateByPrimaryKey(order);
                return;
            }
            LOGGER.info("== 订单未还款，移除订单 ==,orderNo:{}", order.getOrderNo());
            order.setStatus(OrderStatusEnum.removed.getStatus());
            order.setSyncStatus(OrderSyncStatusEnum.need_remove.getStatus());
            ordersDao.updateByPrimaryKey(order);
        });


    }

    @Override
    public void updatePaidOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 开始同步有更新的数据到催收系统 ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_pay_update.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== 开始同步有更新的数据到催收系统 没有还款订单==");
            return;
        }

        LOGGER.info("== 开始同步有更新的数据到催收系统 有还款==,size:{}", todayListBySyncStatusAndAgent.size());
        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());
                String paidAmount = repaymentInfo.get("payMoney").toString();
                ClRepaymentRequest request = new ClRepaymentRequest()
                        .setDeductAmount("0")
                        .setOrderBillNo(order.getCollectionNo())
                        .setPaidAmount(paidAmount)
                        .setPaidStatus(2)
                        .setPaidType(1)
                        .setRepayBizNo(IdUtils.genId() + "")
                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
                        .setTotalDeductAmount("0")
                        .setTotalPaidAmount(paidAmount)
                        .setTradeNo(order.getCollectionNo());

                HttpHeaders headers = new HttpHeaders();
                headers.set("Content-Type", "application/json;charset=utf-8");

                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl(), requestPush, String.class);
                String responseStr = responseEntity.getBody().toString();
                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl());
                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_success.getStatus());
                } else {
                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
                }
            } catch (Exception e) {
                LOGGER.error("=======  推送collection请求结果 error  ======", e);
                order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
            }
            ordersDao.updateByPrimaryKey(order);
        });


    }


    @Override
    public void updateRemovedOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("==  updateRemovedOrderToCollection 开始同步有更新的数据到催收系统==");
    }

    @Override
    public void composeNote(CeCommentPushLogEntity ceCommentPushLogEntity) {
        ceCommentPushLogEntity.setStatus(1);
        commentPushLogDao.updateByPrimaryKey(ceCommentPushLogEntity);
    }


    @Override
    public boolean sendNote(CeCommentPushLogEntity ceCommentPushLogEntity) {

        SivanWalletCollectionTagEnum currentTag = SivanWalletCollectionTagEnum.RNR_V2;

        for (SivanWalletCollectionTagEnum e : SivanWalletCollectionTagEnum.values()) {
            if (e.getType().equals(ceCommentPushLogEntity.getTargetType())) {
                currentTag = e;
            }
        }
        LOGGER.info("== 开始同步催记到甲方 ==");
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceCommentPushLogEntity.getMerchantCode());
        CeAgentAccountEntity account = agentAccountDao.getByAgentCode(ceCommentPushLogEntity.getAgentCode());
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByOrderNo(ceCommentPushLogEntity.getOriginNo());
        Any orderInfo = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        try {
            Map<String, String> headers = getHeaders(account);
            JSONObject params = new JSONObject();
            params.put("remark", currentTag.getShortDesc());
            params.put("overdueId", orderInfo.get("id").toString());

            String url = ceMerchantEntity.getApiDomain() + "/hs/admin/orderToday/addCollection";
            String[] command = {"curl", "--location", "--request", "POST", url, "--header", "Content-Type: application/json", "--header", "Cookie:" + headers.get("cookie") ,"--data-raw", params.toString()};
            String result = execCurl(command);
            LOGGER.info("== 开始同步催记到甲方 ==,res:{}", result);

            if (JsonIterator.deserialize(result).get("code").toInt() == 200) {
                LOGGER.info("== 开始同步催记到甲方 success==");
                return true;
            } else {
                LOGGER.error("== 开始同步催记到甲方 error==");
            }

        } catch (Exception e) {
            LOGGER.error("== 开始同步催记到甲方 exception==", e);
        }
        return false;
    }

    @Override
    public String updateRepaymentLink(String collectionNo, boolean isReduce) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        Any orderInfo = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        String link = "";
        Map<String, String> headers = getHeaders(accountEntity);
        JSONObject params = new JSONObject();
        params.put("isLeng", false);
        String url;
        if (accountEntity.getStage().contains("d")){
            params.put("todayId", orderInfo.get("id").toString());
            url = ceMerchantEntity.getApiDomain() + "/hs/admin/orderToday/sendPaymentLinks";
        }else {
            params.put("overdueId", orderInfo.get("id").toString());
            url = ceMerchantEntity.getApiDomain() + "/hs/admin/orderOverdue/sendPaymentLinks";
        }
        LOGGER.info("== 获取SivanWallet还款链接 ==,url:{}", url);
        String[] command = {"curl", "--location", "--request", "POST", url, "--header", "Content-Type: application/json", "--header", "Cookie:" + headers.get("cookie") ,"--data-raw", params.toString()};
        String result = execCurl(command);
        LOGGER.info("== 获取SivanWallet还款链接 ==,url:{},res:{}", url, result);
        Any resultJson = JsonIterator.deserialize(result);
        if (resultJson.get("code").toInt() == 200) {
            String data = resultJson.get("data").toString();
            link = data.substring(data.indexOf("[") + 1, data.lastIndexOf("]")).replace(" ", "");
            LOGGER.info("== 获取还款链接 ==,link:{}", link);
        } else {
            LOGGER.error("== 获取还款链接失败 ==,account:{},orderNo:{}", ceOrdersEntity.getAgentCode(), ceOrdersEntity.getOrderNo());
            link = "Get Link Failed";
        }
        return link;
    }

    @Override
    public String updateExtensionRepaymentLink(String collectionNo,boolean isOpen) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        String renewLink = "";
        Any orderInfo = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        Map<String, String> headers = getHeaders(accountEntity);
        JSONObject params = new JSONObject();
        params.put("isLeng", true);
        String url;
        if (accountEntity.getStage().contains("d")){
            params.put("todayId", orderInfo.get("id").toString());
            url = ceMerchantEntity.getApiDomain() + "/hs/admin/orderToday/sendPaymentLinks";
        }else {
            params.put("overdueId", orderInfo.get("id").toString());
            url = ceMerchantEntity.getApiDomain() + "/hs/admin/orderOverdue/sendPaymentLinks";
        }
        LOGGER.info("== 获取SivanWallet还款链接 ==,url:{}", url);
        String[] command = {"curl", "--location", "--request", "POST", url, "--header", "Content-Type: application/json", "--header", "Cookie:" + headers.get("cookie") ,"--data-raw", params.toString()};
        String result = execCurl(command);
        LOGGER.info("== 获取SivanWallet还款链接 ==,url:{},res:{}", url, result);
        Any resultJson = JsonIterator.deserialize(result);
        if (resultJson.get("code").toInt() == 200) {
            String data = resultJson.get("data").toString();
            renewLink = data.substring(data.indexOf("[") + 1, data.lastIndexOf("]")).replace(" ", "");
            LOGGER.info("== 获取还款链接 ==,link:{}", renewLink);
        } else {
            LOGGER.error("== 获取还款链接失败 ==,account:{},orderNo:{}", ceOrdersEntity.getAgentCode(), ceOrdersEntity.getOrderNo());
            renewLink = "Get Link Failed";
        }
        return renewLink;
    }

    @Override
    public String addPaymentOrder(String orderNo, String fileName, String fileUrl, String utr, String remark, String amount) {
        return "";
    }


    @Override
    public String queryPaymentOrderResult(String orderNo, String utr) {
        return "";
    }

    @Override
    public String checkOrdersPaid(String orderNo) {
        return null;
    }

    public static void main(String[] args) {
    }

    private static String getBirthDayByAge(Integer age) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();

        c.setTime(new Date());
        c.add(Calendar.YEAR, -age);
        Date y = c.getTime();
        return format.format(y);
    }
}
